// ==UserScript==
// @name         98堂助手
// @namespace    https://gitee.com/huelse/js-scripts/raw/master/98tang.js
// @version      2024-08-27
// @description  98堂助手
// @author       THENDINGs
// @match        https://www.sehuatang.org/*
// @match        https://www.sehuatang.net/*
// @icon         https://www.sehuatang.org/favicon.ico
// @grant        unsafeWindow
// @run-at       document-body
// @license      GPLv3 License
// ==/UserScript==

(function () {
  'use strict';

  let commentContent = '感谢分享！'
  let scoreValue = '+3'
  let isHideImages = false
  let smallImageStyleId = null

  let scrolltop = document.getElementById('scrolltop')
  if (scrolltop) {
    init()
  } else {
    let intervalRef = 0
    let count = 0
    intervalRef = setInterval(() => {
      scrolltop = document.getElementById('scrolltop')
      if (scrolltop) {
        init()
        clearInterval(intervalRef)
      }
      count++
      if (count > 10) {
        console.log(Date.now(), '找不到scrolltop')
        clearInterval(intervalRef)
      }
    }, 2000)
  }

  if (location.href.includes('plugin.php?id=dd_sign')) {
    setTimeout(() => {
      sign()
    }, 2000)
  }

  function init() {
    let defaultStyle = '.custom-nav { background: none !important;display: flex !important;align-items: center;justify-content: center;padding 10px 0; }'
    appendStyle(defaultStyle)

    createNav('小图', function (atag) {
      // console.log(Date.now(), atag.innerText)
      if (smallImageStyleId) {
        atag.innerText = '小图'
        normalImage()
      } else {
        atag.innerText = '大图'
        smallImage()
      }
    })

    createNav('无图', function (atag) {
      // console.log(Date.now(), atag.innerText)
      if (isHideImages) {
        atag.innerText = '无图'
        showImages()
        isHideImages = false
      } else {
        atag.innerText = '显图'
        hideImages()
        isHideImages = true
      }
    })

    createNav('评论', function (atag) {
      // console.log(Date.now(), atag.innerText)
      if (atag.innerText.length === 2) {
        atag.innerText = '处理中...'
        pingLun().then(() => {
          atag.innerText = '评论'
        })
      }
    })

    createNav('评分', function (atag) {
      // console.log(Date.now(), atag.innerText)
      if (atag.innerText.length === 2) {
        atag.innerText = '处理中...'
        pingFen().then(() => {
          atag.innerText = '评分'
        })
      }
    })

    createNav('ED2K', function (atag) {
      // console.log(Date.now(), atag.innerText)
      getEd2k()
    })
  }

  function appendStyle(styleValue) {
    let style = document.createElement('style')
    let sid = (Math.random() + 1).toString(36).substring(7)
    style.id = sid
    style.innerHTML = styleValue
    document.getElementsByTagName('HEAD').item(0).appendChild(style)
    return sid
  }

  function createNav(name, callback) {
    let centerStyle = ''
    let scrolltop = document.getElementById('scrolltop')
    let span = document.createElement('span')
    let atag = document.createElement('a')
    atag.innerText = name
    atag.style = centerStyle
    atag.className = 'custom-nav'
    atag.onclick = function () {
      callback(atag)
    }
    span.appendChild(atag)
    scrolltop.insertAdjacentElement('afterbegin', span)
  }

  function pingFen() {
    return new Promise(resolve => {
      let target = document.getElementById('ak_rate')
      if (target) {
        target.click()

        const doPingFen = (input) => {
          input.value = scoreValue
          setTimeout(() => {
            let btn = document.querySelector('button')
            btn.click()
            console.log(Date.now(), '评分成功')
            resolve()
          }, 2000)
        }

        let input = document.getElementById('score8')
        let inervalRef = 0
        if (input) {
          doPingFen(input)
        } else {
          inervalRef = setInterval(() => {
            console.log(Date.now(), '等待评分窗口')
            input = document.getElementById('score8')
            if (input) {
              clearInterval(inervalRef)
              doPingFen(input)
            }
            let warn = document.getElementById('fwin_content_rate')
            if (warn) {
              clearInterval(inervalRef)
              console.log(Date.now(), '评分失败')
              resolve()
            }
          }, 2000)
        }

      } else {
        resolve()
      }
    })
  }

  function pingLun() {
    return new Promise(resolve => {
      let textarea = document.getElementById('fastpostmessage')
      if (textarea) {
        textarea.value = commentContent
        setTimeout(() => {
          let submit = document.getElementById('fastpostsubmit')
          submit.click()
          console.log(Date.now(), '评论成功')
          resolve()
        }, 2000)
      } else {
        resolve()
      }
    })
  }

  function sign() {
    let signBtn = document.querySelector('.dd_sign a.ddpc_sign_btn_red')
    if (signBtn) {
      console.log(Date.now(), '开始签到')
      signBtn.focus()
      signBtn.click()

      const doSign = (input) => {
        let text = input.parentElement.innerText
        let question = text.split('\n')?.[1]?.split('=')?.[0]
        if (question) {
          let anwswer = eval(question)
          input.focus()
          input.value = anwswer
          setTimeout(() => {
            let submit = document.querySelector('button[name="signsubmit"]')
            submit.focus()
            submit.click()
            console.log(Date.now(), '签到完成')
          }, 2000)
        }
      }

      let input = document.querySelector('input[name="secanswer"]')
      let inervalRef = 0
      let count = 0
      if (input) {
        doSign(input)
      } else {
        inervalRef = setInterval(() => {
          console.log(Date.now(), '等到签到窗口')
          input = document.querySelector('input[name="secanswer"]')
          if (input) {
            clearInterval(inervalRef)
            doSign(input);
          }
          count++
          if (count > 10) {
            console.log(Date.now(), '找不到签到窗口')
            clearInterval(inervalRef)
          }
        }, 2000)
      }
    }
  }

  function copyContent(content) {
    let textarea = document.createElement('textarea')
    document.body.appendChild(textarea)
    textarea.style.position = 'fixed'
    textarea.style.clip = 'rect(0 0 0 0)'
    textarea.style.top = '-100px'
    textarea.value = content
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea);
  }

  function getEd2k() {
    let target = document.querySelector('#postlist .pcb')
    if (target) {
      // 先找ed2k链接
      let urls = target.innerText.match(/ed2k:\/\/.*\//g)

      // 再找附件下载
      let arr = Array.from(document.querySelectorAll('#postlist .pcb a'))
      let attach = arr.find(a => a.href.includes('?mod=attachment'))

      if (urls && urls.length > 0) {
        console.log('ED2K:', urls.length)
        let res = prompt('ED2K', urls.join('\n'))
        if (res) {
          copyContent(urls.join('\n'))
        }
      } else if (attach) {
        scrollTo({
          top: attach.offsetTop,
          behavior: 'smooth'
        })
      } else {
        alert('未找到ED2k链接')
      }

    }
  }

  function hideImages() {
    let blocks = document.querySelectorAll('#postlist ignore_js_op')
    blocks.forEach(block => {
      block.style = 'display: none !important;'
    })
  }

  function showImages() {
    let blocks = document.querySelectorAll('#postlist ignore_js_op')
    blocks.forEach(block => {
      block.removeAttribute('style')
    })
  }

  function smallImage() {
    let style = '#postlist img.zoom { height: 120px;width: auto; }'
    smallImageStyleId = appendStyle(style)
  }

  function normalImage() {
    if (smallImageStyleId) {
      document.getElementById(smallImageStyleId).remove()
      smallImageStyleId = null
    }
  }
})()
